{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "52824b89-532a-4e54-87e9-1410813cd39e",
   "metadata": {},
   "source": [
    "# LangChain: Agents\n",
    "\n",
    "## Outline:\n",
    "\n",
    "* Using built in LangChain tools: DuckDuckGo search and Wikipedia\n",
    "* Defining your own tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b7ed03ed-1322-49e3-b2a2-33e94fb592ef",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "from dotenv import load_dotenv, find_dotenv\n",
    "_ = load_dotenv(find_dotenv()) # read local .env file\n",
    "\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0e3b9ad2",
   "metadata": {},
   "source": [
    "## Built-in LangChain tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "974acf8e-8f88-42de-88f8-40a82cb58e8b",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "#!pip install -U wikipedia"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7b93d0e8",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.agents.agent_toolkits import create_python_agent\n",
    "from langchain.agents import load_tools, initialize_agent\n",
    "from langchain.agents import AgentType\n",
    "from langchain.tools.python.tool import PythonREPLTool\n",
    "from langchain.python import PythonREPL\n",
    "from langchain.chat_models import ChatOpenAI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7aadd5c1",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "llm = ChatOpenAI(temperature=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "394924ac",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "tools = load_tools([\"llm-math\",\"wikipedia\"], llm=llm)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "02cd4956",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "agent= initialize_agent(\n",
    "    tools, \n",
    "    llm, \n",
    "    agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,\n",
    "    handle_parsing_errors=True,\n",
    "    verbose = True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "44601fe4-5f24-4ff2-a5df-a7e194a5b4f8",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent(\"What is the 25% of 300?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "441df699-0a52-4812-a0a7-4605204f0aa8",
   "metadata": {},
   "outputs": [],
   "source": [
    "question = \"Tom M. Mitchell is an American computer scientist \\\n",
    "and the Founders University Professor at Carnegie Mellon University (CMU)\\\n",
    "what book did he write?\"\n",
    "result = agent(question) "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "90299a00-eb79-4755-bb4b-bf61d88c7fed",
   "metadata": {},
   "source": [
    "## Python Agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c7617576-d855-4ede-9c1a-be742f1504cf",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent = create_python_agent(\n",
    "    llm,\n",
    "    tool=PythonREPLTool(),\n",
    "    verbose=True\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d05e7dc6-f07e-43df-a2f6-9a0816291861",
   "metadata": {},
   "outputs": [],
   "source": [
    "customer_list = [[\"Harrison\", \"Chase\"], \n",
    "                 [\"Lang\", \"Chain\"],\n",
    "                 [\"Dolly\", \"Too\"],\n",
    "                 [\"Elle\", \"Elem\"], \n",
    "                 [\"Geoff\",\"Fusion\"], \n",
    "                 [\"Trance\",\"Former\"],\n",
    "                 [\"Jen\",\"Ayai\"]\n",
    "                ]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f887f8f9-216e-489a-945a-f38fbccbe5c4",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent.run(f\"\"\"Sort these customers by \\\n",
    "last name and then first name \\\n",
    "and print the output: {customer_list}\"\"\") "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74466cec-2d98-438b-805f-33e31fdc3035",
   "metadata": {},
   "source": [
    "#### View detailed outputs of the chains"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "12548579-810b-416e-afb5-178296685c2c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import langchain\n",
    "langchain.debug=True\n",
    "agent.run(f\"\"\"Sort these customers by \\\n",
    "last name and then first name \\\n",
    "and print the output: {customer_list}\"\"\") \n",
    "langchain.debug=False"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d2a4685",
   "metadata": {},
   "source": [
    "## Define your own tool"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "70b32cfe",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "#!pip install DateTime"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "73f8b595",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.agents import tool\n",
    "from datetime import date"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "61c64268",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "@tool\n",
    "def time(text: str) -> str:\n",
    "    \"\"\"Returns todays date, use this for any \\\n",
    "    questions related to knowing todays date. \\\n",
    "    The input should always be an empty string, \\\n",
    "    and this function will always return todays \\\n",
    "    date - any date mathmatics should occur \\\n",
    "    outside this function.\"\"\"\n",
    "    return str(date.today())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0d2fd9ee",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "agent= initialize_agent(\n",
    "    tools + [time], \n",
    "    llm, \n",
    "    agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,\n",
    "    handle_parsing_errors=True,\n",
    "    verbose = True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f9f30e7c-77f1-43fc-a966-140f05160378",
   "metadata": {},
   "source": [
    "**Note**: \n",
    "\n",
    "The agent will sometimes come to the wrong conclusion (agents are a work in progress!). \n",
    "\n",
    "If it does, please try running it again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1fcd13cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    result = agent(\"whats the date today?\") \n",
    "except: \n",
    "    print(\"exception on external access\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
